<template>
  <div class="daily-practice-detail-container">
    <div class="header-section">
      <el-button type="primary" plain class="back-btn" @click="goBack">
        <i class="el-icon-arrow-left"></i> 返回训练记录
      </el-button>
      <h1>每日练习详情 - {{ formatDate(practiceDate) }}</h1>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <!-- 添加科目筛选功能 -->
      <div class="filter-item">
        <span class="filter-label">科目：</span>
        <el-select v-model="selectedSubject" placeholder="筛选科目" @change="filterResults">
          <el-option label="全部科目" value=""></el-option>
          <el-option 
            v-for="subject in uniqueSubjects" 
            :key="subject" 
            :label="subject" 
            :value="subject">
          </el-option>
        </el-select>
      </div>
      
      <!-- 添加题目类型筛选 -->
      <div class="filter-item">
        <span class="filter-label">题型：</span>
        <el-select v-model="selectedType" placeholder="筛选题型" @change="filterResults">
          <el-option label="全部题型" value=""></el-option>
          <el-option label="单选题" value="single_choice"></el-option>
          <el-option label="填空题" value="fill_in_the_blank"></el-option>
          <el-option label="主观题" value="subjective"></el-option>
        </el-select>
      </div>
      
      <!-- 添加答题状态筛选 -->
      <div class="filter-item">
        <span class="filter-label">状态：</span>
        <el-select v-model="selectedStatus" placeholder="筛选状态" @change="filterResults">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="正确" value="correct"></el-option>
          <el-option label="错误" value="wrong"></el-option>
          <el-option label="未批改" value="unchecked"></el-option>
        </el-select>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert :title="error" type="error" show-icon />
    </div>
    <div v-else-if="results.length === 0" class="no-results-container">
      <el-empty description="没有找到该次练习的记录" />
    </div>
    
    <div v-else class="content-container">
      <div class="summary-card">
        <div class="summary-item">
          <span class="summary-label">总题数</span>
          <span class="summary-value">{{ results.length }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">正确率</span>
          <span class="summary-value">{{ correctRate }}%</span>
        </div>
      </div>
      
      <div class="results-container">
        <div v-for="(result, index) in filteredResults" :key="index" class="result-card">
          <div class="result-header">
            <el-tag type="info" size="small">{{ result.subject }}</el-tag>
            <el-tag type="info" size="small">{{ result.examType }}</el-tag>
            <el-tag type="info" size="small">{{ getQuestionTypeName(result.questionType) }}</el-tag>
            <el-tag v-if="result.isCorrect !== null" 
                    :type="result.isCorrect ? 'success' : 'danger'" 
                    size="small">
              {{ result.isCorrect ? '正确' : '错误' }}
            </el-tag>
            <el-tag v-else type="warning" size="small">未批改</el-tag>
            <!-- 改进后的收藏按钮 - 使用明显的五角星 -->
            <div class="favorite-star" @click="toggleFavorite(result)">
              <i 
                v-if="!result.loading"
                :class="result.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'" 
                :style="{ color: result.isFavorite ? '#ffc107' : '#c0c4cc' }"
              ></i>
              <i v-else class="el-icon-loading"></i>
              <span class="favorite-text">{{ result.isFavorite ? '已收藏' : '收藏' }}</span>
            </div>
          </div>
          <div class="question-content">
            <span class="question-index">{{ index + 1 }}.</span>
            <div v-html="formatQuestionContent(result.questionContent)" class="question-text"></div>
          </div>
          
          <!-- 修改选择题样式，与MockExamDetail.vue保持一致 -->
          <div v-if="result.questionType === 'single_choice'" class="choices-container">
            <div v-for="(choice, choiceIndex) in parseChoices(result.choices)" 
                 :key="choiceIndex" 
                 class="choice-item"
                 :class="{
                   'user-answer': result.userAnswer === String.fromCharCode(65 + choiceIndex),
                   'correct-answer': result.correctAnswer === String.fromCharCode(65 + choiceIndex),
                   'correct-and-selected': result.userAnswer === String.fromCharCode(65 + choiceIndex) && result.correctAnswer === String.fromCharCode(65 + choiceIndex)
                 }">
              <span class="option-label">{{ String.fromCharCode(65 + choiceIndex) }}.</span>
              <span class="option-text" v-html="formatQuestionContent(choice)"></span>
            </div>
          </div>
          
          <div class="answer-container">
            <div v-if="result.questionType !== 'single_choice'" class="analysis-row">
              <span class="answer-label">您的答案：</span>
              <span class="user-answer" v-html="formatQuestionContent(result.userAnswer || '未作答')"></span>
            </div>
            
            <div class="analysis-row">
              <span class="answer-label">正确答案：</span>
              <span class="correct-answer" v-html="formatQuestionContent(result.correctAnswer || '')"></span>
            </div>
            
            <div v-if="result.analysis" class="analysis-row">
              <span class="answer-label">答案解析：</span>
              <span class="analysis-content" v-html="formatQuestionContent(result.analysis)"></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

// 导入KaTeX
import 'katex/dist/katex.min.css';
import katex from 'katex';

const route = useRoute();
const router = useRouter();
const props = defineProps({
  userId: String,
  practiceId: String
});
const results = ref([]);
const filteredResults = ref([]);
const loading = ref(true);
const error = ref(null);

// 新增筛选状态
const selectedSubject = ref('');
const selectedType = ref('');
const selectedStatus = ref('');

// ====================== LaTeX渲染相关 ======================
/* 格式化题目内容 - 使用KaTeX处理数学公式 */
const formatQuestionContent = (content) => {
  if (!content) return '';

  try {
    // 第一步：预处理（保护SVG路径数据）
    let processedContent = content
      // 临时保护SVG路径数据（将d="..."内容标记起来）
      .replace(/(d="[^"]*")/g, (match) => {
        return match.replace(/<br\s*\/?>/gi, ' '); // 移除SVG路径内的<br>
      })
      // 处理普通换行符（非SVG部分）
      .replace(/\\n/g, '\n')
      // 临时转义美元符号（用于后续LaTeX处理）
      .replace(/\\\$/g, '###DOLLAR###');

    // 第二步：处理LaTeX公式（块级公式 $$...$$）
    processedContent = processedContent.replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula.trim(), {
          displayMode: true,
          throwOnError: false,
          strict: false,
          trust: true
        });
      } catch (error) {
        console.warn('KaTeX块级公式渲染错误:', error, '公式:', formula);
        return `<span class="katex-error">$$${formula}$$</span>`;
      }
    });

    // 第三步：处理LaTeX公式（行内公式 $...$）
    processedContent = processedContent.replace(/\$([^$\n]+)\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula.trim(), {
          displayMode: false,
          throwOnError: false,
          strict: false,
          trust: true
        });
      } catch (error) {
        console.warn('KaTeX行内公式渲染错误:', error, '公式:', formula);
        return `<span class="katex-error">$${formula}$</span>`;
      }
    });

    // 第四步：后处理
    processedContent = processedContent
      // 恢复转义的美元符号
      .replace(/###DOLLAR###/g, '$')
      // 将换行符转为HTML标签（非SVG部分）
      .replace(/\n/g, '<br>')
      // 最终检查（确保没有遗漏的SVG破坏）
      .replace(/(<path [^>]*d="[^"]*")/g, (match) => {
        return match.replace(/<br\s*\/?>/gi, ' ');
      });

    return processedContent;
  } catch (error) {
    console.error('内容格式化失败:', error);
    // 降级处理：简单清理后返回
    return String(content)
      .replace(/<br\s*\/?>/gi, ' ')
      .replace(/\\n/g, '<br>');
  }
};

// 从 practiceId 中提取日期
const practiceDate = computed(() => {
  return props.practiceId.replace('daily_', '');
});

// 返回训练记录页面
const goBack = () => {
  router.push({ name: 'TrainingRecord' });
};

// 获取唯一科目列表
const uniqueSubjects = computed(() => {
  return [...new Set(results.value.map(item => item.subject))];
});

// 筛选结果
const filterResults = () => {
  filteredResults.value = results.value.filter(item => {
    const subjectMatch = selectedSubject.value === '' || item.subject === selectedSubject.value;
    const typeMatch = selectedType.value === '' || item.questionType === selectedType.value;
    
    let statusMatch = true;
    if (selectedStatus.value !== '') {
      if (selectedStatus.value === 'correct') {
        statusMatch = item.isCorrect === true;
      } else if (selectedStatus.value === 'wrong') {
        statusMatch = item.isCorrect === false;
      } else if (selectedStatus.value === 'unchecked') {
        statusMatch = item.isCorrect === null;
      }
    }
    
    return subjectMatch && typeMatch && statusMatch;
  });
};

// 监听结果变化
watch(results, (newVal) => {
  filteredResults.value = [...newVal];
  filterResults();
});

const getQuestionTypeName = (type) => {
  const typeMap = {
    'single_choice': '单选题',
    'fill_in_the_blank': '填空题',
    'subjective': '主观题'
  };
  return typeMap[type] || type;
};

const parseChoices = (choicesString) => {
  if (!choicesString) return [];
  try {
    // 处理可能带A. B. C. D.前缀的选项
    return choicesString.split(',').map(choice => {
      // 移除选项字母前缀（如"A. "）
      return choice.replace(/^[A-D]\.\s*/, '').trim();
    });
  } catch (e) {
    console.error('解析选择题选项失败:', e);
    return [];
  }
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD');
};

// 修改正确率计算：只计算选择题和填空题
const correctRate = computed(() => {
  // 筛选出选择题和填空题
  const gradedQuestions = results.value.filter(item => 
    item.questionType === 'single_choice' || item.questionType === 'fill_in_the_blank'
  );
  
  if (gradedQuestions.length === 0) return 0;
  
  // 计算答对的数量
  const correctCount = gradedQuestions.filter(item => item.isCorrect).length;
  
  // 返回百分比
  return Math.round((correctCount / gradedQuestions.length) * 100);
});

// 切换收藏状态
const toggleFavorite = async (result) => {
  try {
    // 设置加载状态
    result.loading = true;
    
    const newFavoriteStatus = result.isFavorite ? 0 : 1;
    
    const response = await axios.put('/api/daily-practices/favorite', {
      recordId: result.recordId,
      isFavorite: newFavoriteStatus,
      userId: props.userId,
      questionId: result.questionId
    });
    
    if (response.data) {
      result.isFavorite = !result.isFavorite;
      ElMessage.success(result.isFavorite ? '已收藏题目' : '已取消收藏');
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
  } finally {
    result.loading = false;
  }
};

// 获取练习结果
const fetchPracticeResults = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const response = await axios.get('/api/daily-practices/results', {
      params: {
        userId: props.userId,
        practiceId: props.practiceId
      }
    });
    
    // 为每个结果项添加loading状态和默认收藏状态
    results.value = response.data.map(item => ({
      ...item,
      loading: false,
      isFavorite: item.isFavorite || false // 确保有默认值
    }));
  } catch (err) {
    error.value = '获取练习详情失败: ' + (err.response?.data?.message || err.message);
    console.error('获取练习详情失败:', err);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchPracticeResults();
});

</script>

<style scoped>
.daily-practice-detail-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-section {
  position: relative;
  text-align: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.back-btn {
  position: absolute;
  left: 0;
  top: 5px;
  padding: 8px 15px;
}

h1 {
  color: #303133;
  font-size: 20px;
  margin: 0;
  padding: 10px 0;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.filter-item {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 250px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  min-width: 45px;
}

.loading-container,
.error-container,
.no-results-container {
  margin-top: 30px;
}

.content-container {
  margin-top: 20px;
}

.summary-card {
  display: flex;
  justify-content: space-around;
  margin-bottom: 30px;
  padding: 20px 15px;
  background: linear-gradient(135deg, #f0f7ff, #e6f7ff);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.results-container {
  margin-top: 20px;
}

.result-card {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.result-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.result-header {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  align-items: center;
}

.question-content {
  font-size: 16px;
  margin-bottom: 15px;
  line-height: 1.6;
  color: #303133;
  display: flex;
  align-items: baseline;
}

.question-index {
  font-weight: 600;
  margin-right: 8px;
  flex-shrink: 0;
  line-height: 1.6;
}

.question-text {
  flex: 1;
  line-height: 1.6;
}

/* 选择题样式 - 与MockExamDetail.vue保持一致 */
.choices-container {
  margin: 15px 0;
  padding-left: 10px;
  border-left: 3px solid #e6f7ff;
}

.choice-item {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f9fbfd;
  line-height: 1.6;
  border: 1px solid #ebeef5;
  display: flex;
  align-items: baseline;
}

.choice-item.user-answer {
  background-color: #fff1f0;
  border-color: #ffccc7;
}

.choice-item.correct-answer {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

.choice-item.correct-and-selected {
  background-color: #d9f7be;
  border-color: #95de64;
}

.option-label {
  font-weight: bold;
  margin-right: 10px;
  flex-shrink: 0;
  line-height: 1.6;
}

.option-text {
  flex: 1;
  line-height: 1.6;
}

.answer-container {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 6px;
}

.analysis-row {
  margin-bottom: 12px;
  display: flex;
  align-items: baseline;
}

.analysis-row:last-child {
  margin-bottom: 0;
}

.answer-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  line-height: 1.6;
  flex-shrink: 0;
}

.user-answer {
  color: #ff4d4f;
  font-weight: 500;
  flex: 1;
  line-height: 1.6;
}

.correct-answer {
  color: #52c41a;
  font-weight: 500;
  flex: 1;
  line-height: 1.6;
}

.analysis-content {
  color: #606266;
  line-height: 1.6;
  flex: 1;
}

/* 改进后的收藏按钮样式 - 使用明显的五角星 */
.favorite-star {
  margin-left: auto;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.favorite-star:hover {
  background-color: #f5f7fa;
}

.favorite-star i {
  font-size: 18px;
  margin-right: 4px;
  transition: all 0.3s;
}

.favorite-star .el-icon-star-on {
  color: #ffc107;
}

.favorite-star .el-icon-star-off {
  color: #c0c4cc;
}

.favorite-star .el-icon-loading {
  color: #909399;
}

.favorite-star:hover .el-icon-star-off {
  color: #ffc107;
}

.favorite-text {
  font-size: 12px;
  color: #606266;
}

/* KaTeX样式优化 */
:deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

:deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}

@media (max-width: 768px) {
  .daily-practice-detail-container {
    padding: 15px;
  }
  
  .filter-section {
    flex-direction: column;
  }
  
  .filter-item {
    min-width: 100%;
  }
  
  .summary-card {
    flex-direction: column;
    gap: 20px;
  }
  
  .result-header {
    gap: 8px;
  }
  
  .favorite-text {
    display: none;
  }

  .question-content {
    flex-direction: column;
  }

  .question-index {
    margin-bottom: 5px;
  }

  .analysis-row {
    flex-direction: column;
    gap: 5px;
  }

  .answer-label {
    min-width: auto;
  }

  .choice-item {
    flex-direction: column;
    gap: 5px;
  }

  .option-label {
    margin-bottom: 5px;
  }
}
</style>